package com.boc.ewr.bcimp.controller;

import com.boc.ewr.util.MsgCategoryEnum;
import com.boc.ewr.util.file.TxtImportUtil;
import com.boc.ewr.util.file.enumeration.ImportEnum;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : Wzz
 * @create : 2023-04- 19- 12:06
 * @desc :
 */
@Api(tags = "批量导入")
@RestController
@RequestMapping("/batch/import")
@Slf4j
public class BatchImportController {

    @Autowired
    TxtImportUtil util;

    @Autowired
    ISysBaseAPI sysBaseAPI;

    @RequestMapping(value = "/docInput", method = RequestMethod.POST)
    public Result<?> docInput(HttpServletRequest request, HttpServletResponse response) {
        // 过滤选中数据
        String businessType = request.getParameter("businessType");
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        ImportEnum businessEnum = ImportEnum.getByIndex(businessType);
        List<String> urlList = new ArrayList<>();
        try {
            //文件本地化
            //TODO 文件保存路径待确认？
            urlList = util.uploadTxt(request, "");
            if (urlList.size() == 0) {
                return Result.OK("文件导入数量为0，请确认上传文件");
            }
        } catch (Exception e) {
            log.error("文件导入失败！错误信息：{}", e);
            return Result.error("文件导入失败！, {}", e.getMessage());
        }
        //异步操作
        this.onCallback(urlList, businessType, user.getUsername());
        /*try {
            //判断是否可以生成数据
            util.creInfoByBatInfo(businessType);
        } catch (Exception e) {
            log.error("数据生成失败！错误信息：{}", e);
        }*/
        return Result.OK("文件导入成功！");

    }

    /**
     * 为了避免生成数据花费大量时间，使用异步
     * @param urlList
     * @param businessType
     * @param user
     */
    private void onCallback(List<String> urlList, String businessType, String user) {
        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute(() -> {
            try {
                Thread.sleep(1000 * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 这边执行具体的方法
            this.syncDealResult(urlList, businessType, user);

        });
        executor.shutdown();
    }

    private void syncDealResult(List<String> urlList, String businessType, String toUser) {
        ImportEnum businessEnum = ImportEnum.getByIndex(businessType);
        log.info("======【{}】判断是否可以异步生成数据开始=====", businessEnum.getTypeCN());
        boolean msgFlag = true;
        try {
            // 具体操作
            if (businessEnum.getControlService() != null) {
                //存在自动生成的代码,导入的都是execl
                log.info("==============导入execl开始==============");
                Method method = businessEnum.getControlService().getMethod("importExcel", List.class, ImportEnum.class);
                method.invoke(SpringContextUtils.getBean(businessEnum.getControlService()), urlList, businessEnum);
            } else {
                //txt类型的文档
                log.info("==============导入txt开始==============");
                util.importTxt(urlList, businessEnum.getIndex());
            }
            //保存上传文件情况
            util.saveBatchInfo(urlList, businessType);
            log.info("文件导入成功！");

            util.creInfoByBatInfo(businessType);
        } catch (Exception e) {
            msgFlag = false;
            log.error("数据生成失败！错误信息：{}", e);
        }
        log.info("异步生成数据完成！}");

        if (toUser != null) {
            String content = "您的批量导入【"+businessEnum.getTypeCN()+"】已经完成，请及时查看！";
            if(!msgFlag){
                content = "您的批量导入【"+businessEnum.getTypeCN()+"】失败，请联系相关人员排查问题！";
            }
            MessageDTO messageDTO = new MessageDTO(
                    "system",
                    toUser,
                    businessEnum.getTypeCN() + "批量文件导入",
                    content,
                    MsgCategoryEnum.RISK_CHECK.getIndex());
            sysBaseAPI.sendSysAnnouncement(messageDTO);
            log.info("{}，通知完成！}", businessEnum.getTypeCN());
        }

    }

}
